#encoding=utf8
'''
Created on Jun 12, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from sub_info.models import SubInfo, UPDATE_PURPOSE, UPDATE_META, UPDATE_ASSETS,\
    ReviewStatus, Rejection
from app_info.models import SPECIAL_SETTINGS
from utils import api_call
import settings
import json


def get_type(obj):
    version = obj.app.appversion_set.filter(code=obj.version)
    return version[0].get_type_display() if version else ""


def get_purpose(obj, sp="<br />"):
    version = obj.app.appversion_set.filter(code=obj.version)
    if version:
        if version[0].purpose == 'New App':
            return "New App"
        data = str(version[0].purpose).replace('[', '').replace(']', '').\
            replace("u'", '').replace("'", '').split(', ')
        return sp.join([dict(UPDATE_PURPOSE).get(d, "") for d in data])
    return ""


def get_notes(obj, sp='<br />'):
    version = obj.app.appversion_set.filter(code=obj.version)
    return (sp.join(version[0].change_list.splitlines()) or "") if version else ""


def get_product_owner(obj):
    owner = None
    version = obj.app.appversion_set.filter(code=obj.version)
    try:
        owner = version[0].product_owner
    except Exception, e:
        print e
    return owner or 'N/A'


def get_programmer(obj):
    version = obj.app.appversion_set.filter(code=obj.version)
    if version:
        if version[0].programmer:
            return version[0].programmer
    return "Unassigned"


def get_ref_id(obj):
    version = obj.app.appversion_set.filter(code=obj.version)
    return version[0].ref_id or "" if version else ""


def get_display_name(obj):
    extra_info = obj.app.appextrainfo if hasattr(obj.app, 'appextrainfo') else None
    return (extra_info.display_name or "") if extra_info else ""


def get_has_ads(obj):
    version = obj.app.appversion_set.filter(code=obj.version)
    if version:
        return version[0].ads_required == 'Y'
    return False


def get_has_cross_promo(obj):
    version = obj.app.appversion_set.filter(code=obj.version)
    if version:
        return version[0].cross_promo_required == 'Y'
    return False


def get_has_iap(obj):
    version = obj.app.appversion_set.filter(code=obj.version)
    if version:
        return version[0].iap_required == 'Y'
    return False


def get_special_settings(obj, sp="<br />"):
    extra_info = obj.app.appextrainfo if hasattr(obj.app, 'appextrainfo') else None
    if extra_info:
        if extra_info.special:
            data = str(extra_info.special).replace('[', '').replace(']', '').\
                replace("u'", '').replace("'", '').split(', ')
            return sp.join([dict(SPECIAL_SETTINGS).get(d) for d in data])
    return ""


def get_submission_doc_local(obj):
    extra_info = obj.app.appextrainfo if hasattr(obj.app, 'appextrainfo') else None
    return (extra_info.media_local or "") if extra_info else ""


def get_submission_doc_remote(obj):
    extra_info = obj.app.appextrainfo if hasattr(obj.app, 'appextrainfo') else None
    return (extra_info.media_remote or "") if extra_info else ""


def get_update_meta(obj, sp='<br />'):
    if obj.update_meta:
        data = str(obj.update_meta).replace('[', '').replace(']', '').\
            replace("u'", '').replace("'", '').split(', ')
        return sp.join([dict(UPDATE_META).get(d) for d in data])
    return ""


def get_update_assets(obj, sp='<br />'):
    if obj.update_assets:
        data = str(obj.update_assets).replace('[', '').replace(']', '').\
            replace("u'", '').replace("'", '').split(', ')
        return sp.join([dict(UPDATE_ASSETS).get(d) for d in data])
    return ""


def do_sync():
    for obj in SubInfo.objects.filter(validation='V'):
        ctx = {'request_id': obj.request_id, 'create_time': str(obj.create_time),
           'editor': obj.editor, 'app_code': obj.app.prj_code,
           'app_name': obj.app.app_name, 'product_id': obj.app.prd_id,
           'studio_code': obj.app.studio.studio_code,
           'version': obj.version, 'type': get_type(obj),
           'purpose': get_purpose(obj), 'note': get_notes(obj),
           'is_resub': obj.get_is_resub_display(),
           'resub_req': "<br />".join(obj.get_resub_req()),
           'owner': get_product_owner(obj),
           'programmer': get_programmer(obj),
           'ref_id': get_ref_id(obj),
           'app_store': obj.app.app_store, 'bundle_id': obj.app.get_full_bundle_id(),
           'app_id': obj.app.app_id, 'display_name': get_display_name(obj),
           'ads': 'Yes' if get_has_ads(obj) else 'No',
           'ads_requests': '<br />'.join([a.request_id for a in obj.app.adsinfo_set.all()]),
           'cross': 'Yes' if get_has_cross_promo(obj) else 'No',
           'cross_promo_requests': '<br />'.join([a.request_id for a in obj.app.adsinfo_set.filter(cross_promo='Y')]),
           'iap': 'Yes' if get_has_iap(obj) else 'No',
           'iap_requests': '<br />'.join([i.request_id for i in obj.app.iapinfo_set.all()]),
           'settings': get_special_settings(obj),
           'sd_local': get_submission_doc_local(obj),
           'sd_dropbox': get_submission_doc_remote(obj),
           'edsr': obj.edsr, 'price': obj.price,
           'territories': obj.get_territories(),
           'update_meta': get_update_meta(obj),
           'update_assets': get_update_assets(obj),
           'rating': obj.rating, 'notes': obj.notes,
           'release': obj.get_release_display(),
           'validation': obj.get_validation_display(),
           'valid_date': str(obj.valid_date), 'validation_notes': obj.validation_notes,
           'meta_status': 'Done' if obj.meta_status == 'Y' else 'Pending',
           'meta_ready_date': str(obj.meta_ready_date),
           'binary_uploaded_status': 'Done' if obj.binary_upload_status == 'Y' else 'Pending',
           'binary_uploaded_date': str(obj.binary_uploaded_date),
           'status': obj.get_status_display(),
           'app_submit_date': str(obj.app_submit_date),
           'sub_person': obj.sub_person}
        rtn = api_call('%s%s' % (settings.PS_DOMAIN, settings.PS_CREATE_SUB),
            json.dumps({'request': ctx}), 'POST', {'Content-Type': 'application/json'})
        if not rtn.get('code') == 1:
            print rtn.get('msg'), obj.request_id
            continue


def sync_review_status():
    for obj in ReviewStatus.objects.all():
        records = [{'status_before': x.status_before, 'status_after': x.status_after,
                    'editor': x.editor, 'time': str(x.time)}\
                   for x in obj.reviewstatusrecord_set.all()]
        ctx = {'sub_req_id': obj.sub_info.request_id, 'status': obj.status,
               'store_accept_date': str(obj.store_accept_date) if obj.store_accept_date else None,
               'release_date': str(obj.release_date) if obj.release_date else None, 'records': records}
        rtn = api_call('%s%s' % (settings.PS_DOMAIN, '/create_review/'),
            json.dumps(ctx), 'POST', {'Content-Type': 'application/json'})
        if not rtn.get('code') == 1:
            print rtn.get('msg'), obj.sub_info.request_id
            continue


def sync_rejections():
    for obj in Rejection.objects.all():
        reasons = [{'reason': x.reason, 'detail': x.detail} for x in obj.rejreason_set.all()]
        imgs = [{'img': str(y.img), 'desc': y.desc} for y in obj.rejimg_set.all()]
        acts = [{'person': z.person, 'act': z.act, 'date': str(z.date)} for z in obj.rejact_set.all()]
        ctx = {'sub_req_id': obj.sub_info.request_id, 'issue_id': obj.issue_id,
               'editor': obj.editor, 'timestamp': str(obj.timestamp),
               'status': obj.status, 'create_time': str(obj.create_time),
               'reasons': reasons, 'imgs': imgs, 'acts': acts}
        rtn = api_call('%s%s' % (settings.PS_DOMAIN, '/create_rejection/'),
            json.dumps(ctx), 'POST', {'Content-Type': 'application/json'})
        if not rtn.get('code') == 1:
            print rtn.get('msg'), obj.pk
            continue
